package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.*;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.BrandListAdapter;
import com.szgr.baoyin.adapter.ProtectGoodsListAdapter;
import com.szgr.baoyin.model.AddressProtect;
import com.szgr.baoyin.model.BrandType;
import com.szgr.baoyin.model.InvoiceListItem;
import com.szgr.baoyin.model.OrderMember;
import com.szgr.baoyin.model.ProtectAddress;
import com.szgr.baoyin.model.ProtectGoods;
import com.szgr.baoyin.model.RedPacket;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.pay.AccessoryProtectPayActivity;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.PopMenuDate;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 维保订单详情
 */
public class BuyProtectDetailActivity extends BaseActivity implements PopMenuDate.IPopupWindowsConfirm {

    private ProtectAddress addressProtect;
    private List<ProtectGoods> dataPro;
    private Map<String, Object> hashMap;
    private InvoiceListItem invoiceListItem;
    private TextView et_01;
    private TextView et_02;
    private TextView et_03;
    private TextView et_04;
    private TextView et_05;
    private TextView et_06;
    private TextView et_07;
    private TextView et_08;
    private TextView et_09;
    private TextView et_10;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 666:
                    Intent intent = new Intent(BuyProtectDetailActivity.this, AccessoryProtectPayActivity.class);
                    intent.putExtra("pay_sn",(String) msg.obj);
                    intent.putExtra("type",Constant.TYPE_03);
                    startActivity(intent);
                    finish();
                    break;
                case 7878:
                    et_hongbao.setHint("(您还没有红包)");
                    break;
                case 34:
                    invoiceListItem = invoices.get(0);
                    et_01.setText(invoiceListItem.getInv_company());
                    et_02.setText(invoiceListItem.getInv_code());
                    et_03.setText(invoiceListItem.getInv_reg_addr());
                    et_04.setText(invoiceListItem.getInv_reg_phone());
                    et_05.setText(invoiceListItem.getInv_reg_bname());
                    et_06.setText(invoiceListItem.getInv_reg_baccount());
                    et_07.setText(invoiceListItem.getInv_rec_name());
                    et_08.setText(invoiceListItem.getInv_rec_mobphone());
                    et_09.setText(invoiceListItem.getInv_rec_province());
                    et_10.setText(invoiceListItem.getInv_goto_addr());
                    break;
            }
        }
    };
    private ArrayList<BrandType> brandTypes;
    private BrandType currentBrand;
    private NoScrollListView nslv_brand;
    private TextView tv_num;
    private TextView tv_allMoney;
    private OrderMember orderMember;
    private EditText et_dubi;
    private TextView et_hongbao;
    private LinearLayout menuView;
    private WheelView wheelView;
    private Dialog menuDialog;
    private int index = 1;
    private RedPacket selectRedPacket;
    private List<RedPacket> packets;
    private List<InvoiceListItem> invoices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_protect_detail);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("确认订单");
    }

    @Override
    public void initView() {
        packets = new ArrayList<>();
        TextView tv_company = (TextView) findViewById(R.id.buy_protect_company1);
        TextView tv_address = (TextView) findViewById(R.id.buy_protect_address1);
        TextView tv_faren = (TextView) findViewById(R.id.buy_protect_faren1);
        TextView tv_farenPhone = (TextView) findViewById(R.id.buy_protect_faren_phone1);
        TextView tv_changzhang = (TextView) findViewById(R.id.buy_protect_changzhang1);
        TextView tv_czPhone = (TextView) findViewById(R.id.buy_protect_changzhang_phone1);
        TextView tv_tech = (TextView) findViewById(R.id.buy_protect_tech1);
        TextView tv_techPhone = (TextView) findViewById(R.id.buy_protect_tech_phone1);
        findViewById(R.id.my_order_detail_submit1).setOnClickListener(this);

        findViewById(R.id.go_choose_invoice).setOnClickListener(this);

        et_dubi = (EditText) findViewById(R.id.order_doubi);
        et_hongbao = (TextView) findViewById(R.id.order_hongbao);
        et_hongbao.setOnClickListener(this);

        et_01 = (TextView) findViewById(R.id.invoice_01);
        et_02 = (TextView) findViewById(R.id.invoice_02);
        et_03 = (TextView) findViewById(R.id.invoice_03);
        et_04 = (TextView) findViewById(R.id.invoice_04);
        et_05 = (TextView) findViewById(R.id.invoice_05);
        et_06 = (TextView) findViewById(R.id.invoice_06);
        et_07 = (TextView) findViewById(R.id.invoice_07);
        et_08 = (TextView) findViewById(R.id.invoice_08);
        et_09 = (TextView) findViewById(R.id.invoice_09);
        et_10 = (TextView) findViewById(R.id.invoice_10);

        tv_num = (TextView) findViewById(R.id.my_order_detail_num);
        tv_allMoney = (TextView) findViewById(R.id.my_order_detail_all);

        nslv_brand = (NoScrollListView) findViewById(R.id.buy_protect_detail_list_view);
        NoScrollListView nslv_goods = (NoScrollListView) findViewById(R.id.buy_protect_detail_goods_list_view);

        initDialog("请选择红包");

        Intent intent = getIntent();
        if(intent.hasExtra("hashMap") && intent.hasExtra("dataPro") && intent.hasExtra("address")){
            hashMap = (Map<String, Object>) intent.getSerializableExtra("hashMap");

            if(hashMap.containsKey("orderMember")){
                orderMember = (OrderMember) hashMap.get("orderMember");
                et_dubi.setHint("(您总共有" + orderMember.getMember_points() + "个都币)");
            }

            dataPro = (List<ProtectGoods>) intent.getSerializableExtra("dataPro");
            addressProtect = (ProtectAddress) intent.getSerializableExtra("address");

            tv_company.setText(addressProtect.getGsmc());
            tv_address.setText(addressProtect.getArea_info() + addressProtect.getAddress());
            tv_faren.setText(addressProtect.getGsfzr());
            tv_farenPhone.setText(addressProtect.getGsfzr_tel());
            tv_tech.setText(addressProtect.getJsfzr());
            tv_techPhone.setText(addressProtect.getJsfzr_tel());

            ProtectGoods protectGoods = dataPro.get(0);
            tv_num.setText(protectGoods.getGoods_num());
            tv_allMoney.setText(protectGoods.getGoods_total());
            brandTypes = new ArrayList<>();
            for (int i = 0; i < Integer.parseInt(protectGoods.getGoods_num()); i++) {
                brandTypes.add(new BrandType());
            }
            nslv_brand.setAdapter(new BrandListAdapter(this, brandTypes,this));

            nslv_goods.setAdapter(new ProtectGoodsListAdapter(this, dataPro));

        }

        getRedPacket();

        getInvoice();
    }

    private void getInvoice() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_LOAD_INVOICE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-- invoice--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray datas = jsonObject.getJSONArray("datas");
                            Gson gson = new Gson();
                            invoices = gson.fromJson(datas.toString(),new TypeToken<List<InvoiceListItem>>(){}.getType());
                            if(invoices != null && invoices.size() == 0){
                                mHandler.obtainMessage(33).sendToTarget();
                            }else {
                                mHandler.obtainMessage(34).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("vat_hash",(String) hashMap.get("vat_hash"));
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void getRedPacket() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_RED_PACKET,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("--- red --->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            Object voucher_list1 = datas.get("voucher_list");
                            if(voucher_list1 instanceof JSONObject) {
                                JSONObject voucher_list = datas.getJSONObject("voucher_list");
                                Iterator<String> keys = voucher_list.keys();
                                Gson gson = new Gson();
                                while (keys.hasNext()) {
                                    JSONObject jsonObject1 = voucher_list.getJSONObject(keys.next());
                                    RedPacket redPacket = gson.fromJson(jsonObject1.toString(), RedPacket.class);
                                    packets.add(redPacket);
                                }
                            }else if(voucher_list1 instanceof JSONArray){
                                mHandler.obtainMessage(7878).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void copy_submitStep2(){
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(30 * 1000);
        RequestParams params = new RequestParams();
        HashMap<String,Object> map = new HashMap<>();
        ProtectGoods protectGoods = dataPro.get(0);
        map.put("key",MyApplication.getmInstance().getKey());
        map.put("cart_id",protectGoods.getGoods_id() + "|" + protectGoods.getGoods_num());
        map.put("address_id",addressProtect.getAddress_id());
        map.put("vat_hash",hashMap.get("vat_hash"));
        map.put("offpay_hash",hashMap.get("offpay_hash"));
        map.put("pay_name","online");
        map.put("invoice_id",invoiceListItem.getInv_id());
        map.put("voucher","0");
        map.put("goods_is_service", "01");
//        BrandType[] bt = new BrandType[brandTypes.size()];
        for (int i = 0; i < brandTypes.size(); i++) {
            map.put("brand_info[" + i + "][brand]" , brandTypes.get(i).getType());
            map.put("brand_info[" + i + "][make_date]" , brandTypes.get(i).getDate());
        }
//        map.put("brand_info",bt);
        map.put("balance_remain","0");

        System.out.println("------>" + map.toString());

        Iterator<Map.Entry<String, Object>> iterator = map
                .entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            params.put(entry.getKey(), entry.getValue());
        }

        client.post(Constant.URL_ORDER_SUBMIT,params,new JsonHttpResponseHandler("UTF-8"){
            @Override
            public void onFailure(int statusCode, Throwable e, JSONObject errorResponse) {

            }

            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                System.out.println("---123--->" + response.toString());
            }
        });
    }

    private void submitStep2() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_ORDER_SUBMIT,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---order-->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONObject pay_sn = datas.getJSONObject("pay_sn");
                            String pay_sn1 = pay_sn.getString("pay_sn");
                            mHandler.obtainMessage(666,pay_sn1).sendToTarget();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                ProtectGoods protectGoods = dataPro.get(0);
                map.put("key",MyApplication.getmInstance().getKey());
                Gson gson = new Gson();
                String bt = gson.toJson(brandTypes);

                map.put("cart_id",protectGoods.getGoods_id() + "|" + protectGoods.getGoods_num());
                map.put("address_id",addressProtect.getAddress_id());
                map.put("vat_hash",(String) hashMap.get("vat_hash"));
                map.put("offpay_hash",(String) hashMap.get("offpay_hash"));
                map.put("pay_name","online");
                map.put("invoice_id",invoiceListItem.getInv_id());


                if(selectRedPacket != null) {
                    map.put("voucher[6]", selectRedPacket.getVoucher_t_id() + "|6|" + selectRedPacket.getVoucher_price());
                }


                map.put("goods_is_service", "01");
                System.out.println("----brand info--->" + bt);

                for (int i = 0; i < brandTypes.size(); i++) {
                    map.put("brand_info[" + i + "][brand]" , brandTypes.get(i).getType());
                    map.put("brand_info[" + i + "][make_date]" , brandTypes.get(i).getDate());
                }
//                map.put("balance_remain","0");

                String text;
                if(MyTool.isEmpty(et_dubi)){
                    text = "0";
                }else {
                    text = MyTool.getText(et_dubi);
                }
                double money = Double.parseDouble(tv_allMoney.getText().toString().trim());
                if(Integer.parseInt(text) > money){
                    text = ((int)(Math.floor(money))) + "";
                }

                map.put("points[6]", text);
                System.out.println("-----params---->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.go_choose_invoice:
                Intent intent = new Intent(this, InvoiceActivity.class);
                intent.putExtra("vat_hash",(String) hashMap.get("vat_hash"));
                startActivityForResult(intent, 22);
                break;
            case R.id.my_order_detail_submit1:
                nslv_brand.clearFocus();
                if(invoiceListItem == null){
                    ToastUtils.showToast("请准确填写开票资料");
                    return;
                }
                for (BrandType bt : brandTypes) {
                    if(bt.getType() == null || bt.getDate() == null){
                        ToastUtils.showToast("请准确填写机床信息");
                    }
                }

                String member_points;
                if(orderMember != null) {
                    member_points = orderMember.getMember_points();
                }else{
                    member_points = "0";
                }
                String text;
                if(MyTool.isEmpty(et_dubi)){
                    text = "0";
                }else{
                    text = MyTool.getText(et_dubi);
                }
                if(Integer.parseInt(text) > Integer.parseInt(member_points)){
                    ToastUtils.showToast("都币余额不足");
                    return;
                }

                submitStep2();
                break;
            case R.id.order_hongbao:
                if(packets.size() > 0){
                    List<String> strs = new ArrayList<>();
                    for (RedPacket redPacket: packets) {
                        strs.add(redPacket.getVoucher_title() + ":" + redPacket.getDesc());
                    }
                    wheelView.setItems(strs);
                    wheelView.setSeletion(0);
                    menuDialog.show();
                }
                break;
        }
    }

    public void initDialog(String title){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectRedPacket = packets.get(index - 1);
                et_hongbao.setText(selectRedPacket.getVoucher_title() + selectRedPacket.getVoucher_price() + "元");

                menuDialog.dismiss();
                index = 1;
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null){
            switch (resultCode){
                case 33:
                    invoiceListItem = (InvoiceListItem) data.getSerializableExtra("inv_id");
                    et_01.setText(invoiceListItem.getInv_company());
                    et_02.setText(invoiceListItem.getInv_code());
                    et_03.setText(invoiceListItem.getInv_reg_addr());
                    et_04.setText(invoiceListItem.getInv_reg_phone());
                    et_05.setText(invoiceListItem.getInv_reg_bname());
                    et_06.setText(invoiceListItem.getInv_reg_baccount());
                    et_07.setText(invoiceListItem.getInv_rec_name());
                    et_08.setText(invoiceListItem.getInv_rec_mobphone());
                    et_09.setText(invoiceListItem.getInv_rec_province());
                    et_10.setText(invoiceListItem.getInv_goto_addr());
                    break;
            }
        }
    }

    @Override
    public void notifyDataChanged(String date, int request) {
        if(request == 907){
            ToastUtils.showToast("机床出厂日期不能在今天之后");
        }
    }
}
